package com.google.ant.extensions.utils;

import java.util.List;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XPathUtils {

    XPath xpath;

    public XPathUtils() {
        xpath = XPathFactory.newInstance().newXPath();
    }

    public XPathUtils(final Map<String, String> ns) {
        this();

        if (ns != null) {
            xpath.setNamespaceContext(new MapNamespaceContext(ns));
        }
    }

    public XPathUtils(final NamespaceContext ctx) {
        this();
        xpath.setNamespaceContext(ctx);
    }

    public Object getValue(String xpathExpression, Node node, QName type) {
        try {
            return xpath.evaluate(xpathExpression, node, type);
        } catch (Exception e) {
            return null;
        }
    }

    public List<String> getStringList(String xpathExpression, Node node) {
        NodeList list = (NodeList) getValue(xpathExpression, node, XPathConstants.NODESET);
        return XMLUtils.getStringList(list);
    }

    public boolean isExist(String xpathExpression, Node node, QName type) {
        return getValue(xpathExpression, node, type) != null;
    }
}
